<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- CDN -->
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"> -->
    <link rel="stylesheet" href="../../css/bootstrap.min.css">
    <link rel="stylesheet" href="../../css/fontawesome/css/all.min.css">
    <script src="../../css/fontawesome/js/all.min.js"></script>
</head>

<body>
    <h2>用户管理</h2>

    <button class="btn btn-link" data-action="addUser">添加</button>

    <table class="table table-striped">
        <thead>
            <tr class="table-dark">
                <th>用户名</th>
                <th>真实姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>手机</th>
                <th>邮箱</th>
                <th>部门</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="tbodyUsersList">

        </tbody>
    </table>

    <script type="module">
        import PocketBase from '../../js/pocketbase.es.js';
        import _on from '../../js/_on.js';
        import _confirm from '../../js/_confirm.js';
        import _reUrl from '../../js/_reUrl.js';
        const html = String.raw;
        const pb = new PocketBase('http://127.0.0.1:8090');

        _reUrl();

        const gender = {
            1: '男',
            2: '女'
        };

        _on('click', {
            addUser() {
                location.href = "./add-user.html"
            },
            async del() {
                try {
                    await _confirm('确定删除吗？');
                    await pb.collection('users').delete(this.dataset.id);
                    getUsers();
                } catch (error) {
                }
            }
        });

        async function getUsers() {
            try {
                const data = await pb.collection('users').getList(1, 30, {
                    expand: 'department'
                });

                tbodyUsersList.innerHTML = data.items.reduce((r, el) => {
                    r += html`<tr>
                        <td>${el.username}</td>    
                        <td>${el.name}</td>   
                        <td>${el.age}</td>   
                        <td>${gender[el.gender]}</td>   
                        <td>${el.phone}</td>   
                        <td>${el.email}</td>   
                        <td>${el.expand.department?.label || '无'}</td>
                        <td> <a href="./edit-user.html?id=${el.id}"  class="btn btn-link">编辑</a> <button data-id="${el.id}" data-action="del" class="btn btn-link">删除</button> </td>
                    </tr>`
                    return r;
                }, '');
            } catch (error) {
                console.log(error);
            }
        }
        getUsers();

    </script>

</body>

</html>